/*
 * Strategy - Sistema Web
 * Copyright 2011-2012
 *
 * Autor               : Vanie Torres
 * Fecha Registro      : 28/10/2012 03:16:12 PM
 * Descripción         : UtilFaces
 */

package com.strategy.modulo.web.util;

/**
 *
 * @author Vanie Torres
 */
import com.strategy.data.util.AuditoriaData;
import com.strategy.modulo.administracion.ejb.ControlStrategyEjbRemote;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ResourceBundle;

import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.ApplicationFactory;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.faces.webapp.UIComponentTag;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Clase que tiene metodos public y static, que son invocados desde otras clases
 * (beans) Brinda funcionalidades que son consideradas genericas.
 */
public class UtilFaces {

    public UtilFaces() {
    }

    public static Object findEjb(String tName)
    {
        Object obj = null;
        ControlStrategyEjbRemote controlStrategyEjb;
       
        try {
            InitialContext initContext  = new InitialContext();
            if (tName.equals("controlStrategyEjb")) {
                controlStrategyEjb =
                (ControlStrategyEjbRemote) initContext.lookup("com.strategy.modulo.administracion.ejb.ControlStrategyEjbRemote");
                obj = controlStrategyEjb;
            } 
        }
        catch (Exception e) {
            return obj;
        }
        return obj;
    }

    public static Object findBean(String tBeanName) {
        Object obj = null;
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext ext = context.getExternalContext();
        Map mapBeans = ext.getSessionMap();
        obj = mapBeans.get(tBeanName);
        return obj;
    }

    public static Object putBeanSession(Class tClass, String tBeanName) {
        Object obj = null;
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext ext = context.getExternalContext();
        Map mapBeans = ext.getSessionMap();
        obj = mapBeans.get(tBeanName);
        if (obj == null) {
            try {
                obj = tClass.newInstance();
                mapBeans.put(tBeanName, obj);
            } catch (InstantiationException ex) {
                Logger.getLogger(UtilFaces.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(UtilFaces.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return obj;
    }

    public static AuditoriaData findRegisterBeanAuditor() {
        Object obj = findBean("auditoria");
        if (obj == null) {
            AuditoriaData auditoria = new AuditoriaData();
            obj = auditoria;
            registerBean(obj, "auditoria");
        }
        return (AuditoriaData) obj;
    }

    public static AppReport findRegisterBeanReport() {
        Object obj = findBean("report");
        if (obj == null) {
            AppReport report = new AppReport();
            obj = report;
            registerBean(obj, "report");
        }
        return (AppReport) obj;
    }

    public static void registerBean(Object tObjBean, String tBeanName) {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext ext = context.getExternalContext();
        Map mapBeans = ext.getSessionMap();
        mapBeans.put(tBeanName, tObjBean);
    }

    public static void addInfoStringMessageBean(String tMsg){
        FacesContext context = FacesContext.getCurrentInstance();
        FacesMessage fm = new FacesMessage(tMsg);
        fm.setSeverity(FacesMessage.SEVERITY_INFO);
        context.addMessage(null, fm);
    }

    public static void addInfoStringsMessageBean(List<String> tMsg){
        FacesContext context = FacesContext.getCurrentInstance();
        FacesMessage fm = null;
        for (String msg : tMsg) {
            fm = new FacesMessage(msg);
            fm.setSeverity(FacesMessage.SEVERITY_INFO);
            context.addMessage(null, fm);
        }
    }

    public static void addErrorStringMessageBean(String tMsg){
        FacesContext context = FacesContext.getCurrentInstance();
        FacesMessage fm = new FacesMessage(tMsg);
        fm.setSeverity(FacesMessage.SEVERITY_ERROR);
        context.addMessage(null, fm);
    }

    public static void addErrorStringsMessageBean(List<String> tMsg){
        FacesContext context = FacesContext.getCurrentInstance();
        FacesMessage fm = null;
        for (String msg : tMsg) {
            fm = new FacesMessage(msg);
            fm.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage(null, fm);
        }
    }

     /**
     * Get servlet context.
     *
     * @return the servlet context
     */
    public static ServletContext getServletContext() {
        return (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
    }

    /**
     * Get managed bean based on the bean name.
     *
     * @param beanName
     *            the bean name
     * @return the managed bean associated with the bean name
     */
    @SuppressWarnings("deprecation")
    public static Object getManagedBean(String beanName) {
        Object o = getValueBinding(getJsfEl(beanName)).getValue(
                FacesContext.getCurrentInstance());

        return o;
    }

    /**
     * Remove the managed bean based on the bean name.
     *
     * @param beanName
     *            the bean name of the managed bean to be removed
     */
    @SuppressWarnings("deprecation")
    public static void resetManagedBean(String beanName) {
        getValueBinding(getJsfEl(beanName)).setValue(
                FacesContext.getCurrentInstance(), null);
    }

    /**
     * Store the managed bean inside the session scope.
     *
     * @param beanName
     *            the name of the managed bean to be stored
     * @param managedBean
     *            the managed bean to be stored
     */
    // @SuppressWarnings("unchecked")
    public static void setManagedBeanInSession(String beanName,
            Object managedBean) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(beanName, managedBean);
    }

    /**
     * Get parameter value from request scope.
     *
     * @param name
     *            the name of the parameter
     * @return the parameter value
     */
    public static String getRequestParameter(String name) {
        return (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(name);
    }

    /**
     * Evaluate the integer value of a JSF expression.
     *
     * @param el
     *            the JSF expression
     * @return the integer value associated with the JSF expression
     */
    @SuppressWarnings("deprecation")
    public static Integer evalInt(String el) {
        if (el == null) {
            return null;
        }

        if (UIComponentTag.isValueReference(el)) {
            Object value = getElValue(el);

            if (value == null) {
                return null;
            } else if (value instanceof Integer) {
                return (Integer) value;
            } else {
                return new Integer(value.toString());
            }
        } else {
            return new Integer(el);
        }
    }

    private static Application getApplication() {
        ApplicationFactory appFactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
        return appFactory.getApplication();
    }

    @SuppressWarnings("deprecation")
    private static ValueBinding getValueBinding(String el) {
        return getApplication().createValueBinding(el);
    }

    public static HttpServletRequest getServletRequest() {
        return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    }

    @SuppressWarnings("deprecation")
    private static Object getElValue(String el) {
        return getValueBinding(el).getValue(FacesContext.getCurrentInstance());
    }

    private static String getJsfEl(String value) {
        return "#{" + value + "}";
    }

    public static String getMessageByKey(String key) {
        try {
            String messageBundleName = FacesContext.getCurrentInstance().getApplication().getMessageBundle();
            ResourceBundle resourceBundle = ResourceBundle.getBundle(messageBundleName);

            return resourceBundle.getString(key);
        } catch (Exception e) {
            return key;
        }

    }

    public static String getUrlActual() {
        return getServletRequest().getRequestURL().toString();
    }

    public static String getDireccionRemota() {
        return getServletRequest().getRemoteAddr();
    }

    /**
     * Convenience method to get the application's URL based on request
     * variables.
     */
    public static String getUrlAplicacion() {

        HttpServletRequest peticion = getServletRequest();

        StringBuffer url = new StringBuffer();
        int port = peticion.getServerPort();
        if (port < 0) {
            port = 80; // Work around java.net.URL bug
        }
        String scheme = peticion.getScheme();
        url.append(scheme);
        url.append("://");
        url.append(peticion.getServerName());
        if ((scheme.equals("http") && (port != 80))
                || (scheme.equals("https") && (port != 443))) {
            url.append(':');
            url.append(port);
        }
        url.append(peticion.getContextPath());
        return url.toString();
    }

    /**
     * Retorna la session web.
     *
     * @return
     */
    public static HttpSession getSession() {
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) ec.getRequest();
        HttpSession session = request.getSession();
        return session;
    }
}

